package com.ruoyi.blog.web;

import com.ruoyi.blog.pojo.Message;
import com.ruoyi.blog.service.MessageService;
import com.ruoyi.blog.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
public class MessageController {

    @Autowired
    private MessageService messageService;
    @Autowired
    private IdWorker idWorker;

    /**
     * 留言页
     */
    @GetMapping("/message")
    public String message(Map<String, Object> map, HttpServletRequest request) {
        List<Message> message = messageService.findAll();
        map.put("message", message);
        return "message";
    }

    @PostMapping("/msgAdd")
    public String messageAdd(Message message, HttpServletRequest request) {
        String id = idWorker.nextId()+"";
        message.setId(id);
        message.setCai("0");
        message.setCommend("0");
        message.setCreateDate(new Date());
        String ipAddress = "";
        if (request.getHeader("x-forwarded-for") == null) {
            ipAddress = request.getRemoteAddr();
            message.setCreateIp(ipAddress);
        }
        messageService.save(message);
        // 添加完成后返回列表页面
        return "redirect:/message";
    }

    /**
     * 点赞
     * @param id
     * @return
     */
    @GetMapping("/commend/{id}")
    public String commend(@PathVariable("id") String id) {
        Message message = messageService.getById(id);
        int i = Integer.parseInt(message.getCommend());
        message.setCommend((i+1)+"");
        messageService.updateById(message);
        return "redirect:/message";
    }

    /**
     * 踩
     * @param id
     * @return
     */
    @GetMapping("/cai/{id}")
    public String cai(@PathVariable("id") String id) {
        Message message = messageService.getById(id);
        int i = Integer.parseInt(message.getCai());
        message.setCai((i+1)+"");
        messageService.updateById(message);
        return "redirect:/message";
    }

}
